﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaseDI
{
    class Program
    {
        static void Main(string[] args)
        {
            //紧耦合的依赖注入演示
            ManagementPerson_A demoA = new ManagementPerson_A(new Employee());
            Console.WriteLine(demoA.GetName());
            //松耦合的依赖注入演示
            ManagementPerson_B demoB = new ManagementPerson_B();
            Console.WriteLine(demoB.GetName());
            Console.ReadKey(true);
        }
    }

    interface IPerson
    {
        string GetName();
    }

    class Employee : IPerson
    {

        public string GetName()
        {
            return "得到员工的名字！";
        }
    }

    class Student : IPerson
    {

        public string GetName()
        {
            return "得到学生的名字！";
        }
    }

    class ManagementPerson_A
    {
        private readonly IPerson _person;

        public ManagementPerson_A(IPerson person)
        {
            _person = person;
        }

        public string GetName()
        {
            return _person.GetName();
        }
    }

    class ManagementPerson_B
    {
        private readonly IPerson _person;

        public ManagementPerson_B()
        {
            _person = PersonFactory.CreatePerson();
        }

        public string GetName()
        {
            return _person.GetName();
        }
    }

    class PersonFactory
    {
        public static IPerson CreatePerson()
        {
            string className = ConfigurationManager.AppSettings["className"];
            switch (className)
            {
                case "Employee": return new Employee();
                case "Student": return new Student();
                default: return new Employee();
            }
        }
    }
}
